<template>
  <div class="content-box card" style="position: relative; padding: 0">
    <div class="left-box">
      <div class="title">
        照护计划模板
        <el-button
          plain
          size="default"
          type="primary"
          style="position: absolute; top: 50%; right: 30px; transform: translateY(-50%)"
          @click="addCarePlanTemplateHandle"
          v-auth="'care_plan_template_save'"
        >
          <el-icon><Plus /></el-icon>
          新增照护计划模板
        </el-button>
      </div>
      <div class="left-table">
        <el-table :data="tableData" style="width: 100%" height="100%" border>
          <el-table-column label="模板来源" width="97" align="center">
            <template #default="scope">
              <span v-if="scope.row.companyId == 1">
                <el-tag type="success" effect="dark" size="small">平台推荐</el-tag>
              </span>
              <span v-else>
                <el-tag type="primary" effect="dark" size="small">自建模板</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="模板名称" width="*" />
          <el-table-column fixed="right" label="操作" width="190" align="center">
            <template #default="scope">
              <el-button link type="primary" @click="getDetail(scope.row.id, '查看')" size="small">查看</el-button>
              <el-button
                link
                type="primary"
                @click="getDetail(scope.row.id, '编辑')"
                size="small"
                v-if="companyId == scope.row.companyId"
                v-auth="'care_plan_template_save'"
              >
                编辑
              </el-button>
              <el-button
                link
                type="primary"
                @click="copyCarePlanTemplateHandle(scope.row)"
                size="small"
                v-auth="'care_plan_template_save'"
              >
                复制
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                v-if="companyId == scope.row.companyId"
                @click="deleteCarePlanTemplateEventHandle(scope.row)"
                v-auth="'care_plan_template_remove'"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="right-box">
      <div class="title">{{ title }}</div>
      <div class="detail-box">
        <div class="detail-item">
          <div class="item-nme">模板名称</div>
          <div class="item-context">
            <el-input
              :disabled="isView"
              ref="carePlanTemplateNameRef"
              v-model="detailData.name"
              style="width: 100%"
              placeholder="请输入照护计划模板名称"
            />
          </div>
        </div>
        <div class="detail-item">
          <div class="item-nme" style="position: relative">
            照护项目
            <el-button
              size="default"
              type="primary"
              @click="openSelectCareMissionDrawer"
              v-if="isEdit"
              icon="Document"
              plain
              style="position: absolute; top: 50%; left: 90px; transform: translateY(-50%)"
            >
              选择照护项目
            </el-button>
          </div>
          <div class="item-context">
            <div>
              <el-table :span-method="objectSpanMethod" :data="detailCareMissionList" border>
                <el-table-column prop="name" label="建议实施时段" width="170" align="center" fixed="left">
                  <template #default="scope">
                    <div v-if="scope.row.isDailyMission">
                      每日：
                      <span v-if="scope.row.dailyMissionStartTime && scope.row.dailyMissionEndTime">
                        {{ scope.row.dailyMissionStartTime }} - {{ scope.row.dailyMissionEndTime }}
                      </span>
                      <span v-else> 不限制时间段 </span>
                    </div>

                    <span v-else> 根据需求及老人情况 </span>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="项目名称" width="350" />
                <el-table-column prop="dailyMissionExecutionCount" label="建议执行次数" width="130" align="center">
                  <template #default="scope">
                    <span v-if="scope.row.dailyMissionExecutionCount">{{ scope.row.dailyMissionExecutionCount }} 次</span>
                    <span v-else> -- </span>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="注意事项" min-width="500" />
                <el-table-column fixed="right" label="操作" width="140" align="center">
                  <template #default="scope">
                    <el-button link type="primary" size="small" @click="editMission(scope.row)" icon="Edit" v-if="isEdit">
                      编辑
                    </el-button>
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click="handleDeleteMission(scope.row.id)"
                      icon="Delete"
                      v-if="isEdit"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <div class="detail-item" style="top: revert; bottom: 153px; height: 180px">
          <div class="item-nme">个性化照护需求</div>
          <div class="item-context">
            <el-input
              :disabled="isView"
              v-model="detailData.personalizedCareNeeds"
              :rows="5"
              type="textarea"
              style="width: 100%"
              placeholder="请输入个性化照护需求内容"
            />
          </div>
        </div>
        <div class="detail-item" style="top: revert; bottom: 85px" v-if="isEdit" v-auth="'care_plan_template_save'">
          <div class="item-context">
            <el-button type="primary" size="default" icon="Finished" @click="save">保存照护计划模板</el-button>
            <el-button type="danger" size="default" icon="Delete" @click="addCarePlanTemplateHandle">清空照护计划模板</el-button>
          </div>
        </div>
      </div>
    </div>

    <SelectCareMissionDrawer ref="selectCareMissionDrawerRef" @change="selectedMissionsChangeCallback" />
    <EditCareMissionDrawer ref="editCareMissionDrawerRef" @change="editMissionChangeCallback" />
  </div>
</template>
<script lang="ts" setup>
import {
  getCarePlanTemplateList,
  getCarePlanTemplateDetail,
  saveCarePlanTemplate,
  deleteCarePlanTemplate,
  copyCarePlanTemplate
} from "@/api/modules/care-plan-template";
import { CareMission } from "@/api/interface";
import type { CarePlanTemplate } from "@/api/interface";
import { onMounted, ref } from "vue";
import SelectCareMissionDrawer from "@/views/care/plan-template/components/SelectCareMissionDrawer.vue";
import EditCareMissionDrawer from "./components/EditCareMissionDrawer.vue";
import { ElMessage, ElMessageBox, TableColumnCtx } from "element-plus";
import { useUserStore } from "@/stores/modules/user";

const isView = ref<boolean>(false);
const isEdit = ref<boolean>(true);
const companyId = ref<number>(0);
const title = ref<string>("新增照护计划模板");
onMounted(async () => {
  await loadList();
  const userStore = useUserStore();
  companyId.value = userStore.userInfo.companyId || 0;
});

// 照护计划模板列表
const tableData = ref<CarePlanTemplate.ResCarePlanTemplate[]>([]);
const loadList = async () => {
  const res = await getCarePlanTemplateList();
  tableData.value = res.data || [];
};

// 照护计划模板详情
const detailData = ref<CarePlanTemplate.ResCarePlanTemplate>({
  missionList: [] as CarePlanTemplate.ResCarePlanTemplateMissionDto[]
} as CarePlanTemplate.ResCarePlanTemplate);
const detailCareMissionList = ref<CarePlanTemplate.ResCarePlanTemplateMissionDto[]>([]);
const carePlanTemplateNameRef = ref<any>();
const getDetail = async (id: number, type: string) => {
  carePlanTemplateNameRef.value.focus();
  const res = await getCarePlanTemplateDetail(id);
  detailData.value = res.data;
  detailCareMissionList.value = JSON.parse(JSON.stringify(detailData.value.missionList || "[]"));
  isView.value = type === "查看";
  isEdit.value = type === "编辑";
  title.value = type === "查看" ? "照护计划模板详情" : "编辑照护计划模板";
};

// 删除照护项目
const handleDeleteMission = (id: number) => {
  // 处理显示列表数据
  let newDetailCareMissionList = JSON.parse(JSON.stringify(detailCareMissionList.value.filter(item => item.id !== id)));
  newDetailCareMissionList = sortMissionList(newDetailCareMissionList);
  detailCareMissionList.value = [];
  detailCareMissionList.value = newDetailCareMissionList;

  // 处理保存列表数据
  for (let i = 0; i < detailData.value.missionList.length; i++) {
    if (detailData.value.missionList[i].id === id) {
      detailData.value.missionList[i].isDelete = 1;
    }
  }
};

// 新增照护项目
const selectCareMissionDrawerRef = ref<InstanceType<typeof SelectCareMissionDrawer> | null>(null);
// 打开选择照护项目抽屉
const openSelectCareMissionDrawer = () => {
  selectCareMissionDrawerRef.value?.acceptParams({ drawerVisible: true, title: "选择照护项目" });
};

// 处理选择照护项目事件
const selectedMissionsChangeCallback = (selectedMissions: CareMission.ResCareMission[]) => {
  let timestampId: number = Date.now();
  let newDetailCareMissionList = JSON.parse(JSON.stringify(detailCareMissionList.value));
  selectedMissions.forEach(m => {
    timestampId = timestampId + 1;
    let mission: CarePlanTemplate.ResCarePlanTemplateMissionDto = {
      id: timestampId,
      categorizeId: m.categorizeId,
      dailyMissionStartTimeValue: m.dailyMissionStartTimeValue,
      dailyMissionEndTimeValue: m.dailyMissionEndTimeValue,
      careMissionId: m.id,
      name: m.name,
      description: m.description,
      isDailyMission: m.isDailyMission,
      dailyMissionStartTime: m.dailyMissionStartTime,
      dailyMissionEndTime: m.dailyMissionEndTime,
      dailyMissionExecutionCount: m.dailyMissionExecutionCount,
      isDelete: 0
    };
    // 添加到显示列表
    newDetailCareMissionList.push(mission);
    // 添加到保存列表
    detailData.value.missionList?.push(JSON.parse(JSON.stringify(mission)));
  });
  newDetailCareMissionList = sortMissionList(newDetailCareMissionList);
  detailCareMissionList.value = [];
  detailCareMissionList.value = newDetailCareMissionList;
};

// 排序照护项目列表
const sortMissionList = (missions: CarePlanTemplate.ResCarePlanTemplateMissionDto[]) => {
  const sortedMissions = missions.sort(
    (a: CarePlanTemplate.ResCarePlanTemplateMissionDto, b: CarePlanTemplate.ResCarePlanTemplateMissionDto) => {
      // 第一优先级：按isDailyMission倒序（1在前，0在后）
      if (a.isDailyMission !== b.isDailyMission) {
        return b.isDailyMission - a.isDailyMission;
      }

      // 第二优先级：按dailyMissionStartTimeValue升序
      // 处理undefined值，将undefined视为最大值排在后面
      if (a.dailyMissionStartTimeValue === undefined && b.dailyMissionStartTimeValue === undefined) {
        return 0;
      }
      if (a.dailyMissionStartTimeValue === undefined) {
        return 1;
      }
      if (b.dailyMissionStartTimeValue === undefined) {
        return -1;
      }

      return a.dailyMissionStartTimeValue - b.dailyMissionStartTimeValue;
    }
  );
  return sortedMissions;
};

// 保存照护计划模板
const save = async () => {
  // 校验
  if (!detailData.value.name) {
    ElMessage({
      message: "请输入照护计划模板名称",
      type: "warning"
    });
    carePlanTemplateNameRef.value.focus();
    return;
  }

  const data: CarePlanTemplate.ReqSaveCarePlanTemplateParams = {
    id: detailData.value.id,
    name: detailData.value.name,
    personalizedCareNeeds: detailData.value.personalizedCareNeeds,
    sort: detailData.value.sort,
    missionList: detailData.value.missionList || []
  };
  const res = await saveCarePlanTemplate(data);
  await getDetail(res.data, "编辑");

  ElMessage({
    message: "保存成功",
    type: "success"
  });
  await loadList();
};

// 新增照护计划模板
const addCarePlanTemplateHandle = () => {
  detailData.value = {} as CarePlanTemplate.ResCarePlanTemplate;
  detailData.value.missionList = [];
  detailCareMissionList.value = [];
  isView.value = false;
  isEdit.value = true;
  carePlanTemplateNameRef.value.focus();
  title.value = "新增照护计划模板";
};

// 删除照护计划模板
const deleteCarePlanTemplateEventHandle = async (item: CarePlanTemplate.ResCarePlanTemplate) => {
  ElMessageBox.confirm(`确定删除照护计划模板【${item.name}】吗？`, "删除提醒", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    await deleteCarePlanTemplate(item.id);
    await loadList();
    if (item.id === detailData.value.id) {
      addCarePlanTemplateHandle();
    }
    ElMessage({
      message: "删除成功",
      type: "success"
    });
  });
};

// 编辑照护项目抽屉
const editCareMissionDrawerRef = ref<InstanceType<typeof EditCareMissionDrawer> | null>(null);
const editMission = (row: CarePlanTemplate.ResCarePlanTemplateMissionDto) => {
  const careMission = JSON.parse(JSON.stringify(row)) as CarePlanTemplate.ResCarePlanTemplateMissionDto;
  editCareMissionDrawerRef.value?.acceptParams({ drawerVisible: true, title: "编辑照护项目", row: careMission });
};

// 编辑照护项目回调
const editMissionChangeCallback = (row: CarePlanTemplate.ResCarePlanTemplateMissionDto) => {
  // 查找并更新 detailCareMissionList 中的对应项
  let newDetailCareMissionList = JSON.parse(JSON.stringify(detailCareMissionList.value));
  for (let i = 0; i < newDetailCareMissionList.length; i++) {
    if (newDetailCareMissionList[i].id === row.id) {
      newDetailCareMissionList[i] = JSON.parse(JSON.stringify(row));
    }
  }
  newDetailCareMissionList = sortMissionList(newDetailCareMissionList);
  detailCareMissionList.value = [];
  detailCareMissionList.value = newDetailCareMissionList;

  // 查找并更新 detailData.value.missionList 中的对应项
  for (let i = 0; i < detailData.value.missionList?.length; i++) {
    if (detailData.value.missionList[i].id === row.id) {
      detailData.value.missionList[i] = JSON.parse(JSON.stringify(row));
    }
  }
};

// 复制照护计划模板
const copyCarePlanTemplateHandle = async (row: CarePlanTemplate.ResCarePlanTemplate) => {
  await copyCarePlanTemplate({ id: row.id, name: row.name + "-副本" });
  ElMessage({
    message: "复制成功",
    type: "success"
  });
  await loadList();
};

// 表格合并行方法
interface SpanMethodProps {
  row: CarePlanTemplate.ResCarePlanTemplateMissionDto;
  column: TableColumnCtx<CarePlanTemplate.ResCarePlanTemplateMissionDto>;
  rowIndex: number;
  columnIndex: number;
}
// 合并行方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  console.log(row, column, rowIndex, columnIndex);
  if (columnIndex === 0) {
    // 只合并第一列
    // 计算相同时间段的连续行数
    let rowspan = 1;
    for (let i = rowIndex + 1; i < detailCareMissionList.value.length; i++) {
      const current = detailCareMissionList.value[i];
      const prev = detailCareMissionList.value[i - 1];

      if (
        current.dailyMissionStartTimeValue === prev.dailyMissionStartTimeValue &&
        current.dailyMissionEndTimeValue === prev.dailyMissionEndTimeValue &&
        current.isDailyMission === prev.isDailyMission
      ) {
        rowspan++;
      } else {
        break;
      }
    }

    // 如果是合并区域的第一行，返回合并的行数
    if (
      rowIndex === 0 ||
      row.dailyMissionStartTimeValue !== detailCareMissionList.value[rowIndex - 1].dailyMissionStartTimeValue ||
      row.dailyMissionEndTimeValue !== detailCareMissionList.value[rowIndex - 1].dailyMissionEndTimeValue ||
      row.isDailyMission !== detailCareMissionList.value[rowIndex - 1].isDailyMission
    ) {
      return {
        rowspan: rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};
</script>
<style scoped lang="scss">
.content-box {
  position: relative;
}
.left-box {
  position: absolute;
  top: 0;
  left: 0;
  width: 500px;
  height: 100%;
  border-right: 1px solid var(--el-aside-border-color);
}
.left-box .title {
  position: absolute;
  top: 0;
  left: 0;
  width: 500px;
  height: 55px;
  padding-left: 17px;
  line-height: 55px;
}
.left-box .left-table {
  position: absolute;
  top: 55px;
  bottom: 0;
  left: 0;
  width: 500px;
}
.right-box {
  position: absolute;
  inset: 0 0 0 500px;
}
.right-box .title {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  width: 100%;
  height: 55px;
  padding-left: 17px;
  line-height: 55px;
  border-bottom: 1px solid var(--el-aside-border-color);
}
.right-box .detail-box {
  position: absolute;
  inset: 55px 0 10px 10px;
  overflow: auto;
}
.right-box .detail-box .detail-item {
  margin-top: 10px;
  border: 1px solid var(--el-aside-border-color);
}
.right-box .detail-box .detail-item .item-nme {
  height: 50px;
  padding-left: 10px;
  line-height: 48px;
  background-color: var(--el-color-primary-light-9);
}
.right-box .detail-box .detail-item .item-context {
  padding: 10px;
}
</style>
